/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.ufms.facom.locadora.ws.dao;

import br.com.caelum.vraptor.Resource;
import br.ufms.facom.locadora.ws.SituacaoDeUmItem;
import br.ufms.facom.locadora.ws.exception.InternalServerErroException;
import br.ufms.facom.locadora.ws.exception.NaoEncontradoException;
import br.ufms.facom.locadora.ws.exception.WebServiceException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 *
 * @author jairo_filho
 */
@Resource
public class ItemDao {
    
    private Connection connection;

    public ItemDao(Connection connection) {
        this.connection = connection;
    }

    public SituacaoDeUmItem consultarSituacaoDeUmItem(String id) {
        try {
            
            PreparedStatement stmt =
                    connection.prepareStatement("select i.estado from item i where i.numeroserie=? limit 1");
            
            stmt.setString(1, id);
            
            ResultSet rs = stmt.executeQuery();
            
            if (rs.next() == false) {
                throw new NaoEncontradoException(String.format("Item '%s' não foi encontrado!", id));
            }
            
            return new SituacaoDeUmItem(id, rs.getString(1));
        
        } catch (WebServiceException ex) {
            throw ex;
        } catch (SQLException ex) {
            throw new InternalServerErroException("Problema no acesso ao banco de dados!", ex);
        }
        
    }
}
